package com.mazaiting.auth.security.custom.enhancer;

import cn.hutool.core.util.StrUtil;
import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.auth.security.core.userdetails.member.MemberUserDetails;
import com.mazaiting.auth.security.core.userdetails.user.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT 内容增强器 - 转换
 */
@Slf4j
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Object principal = authentication.getPrincipal();
        log.debug("类型: " + principal);
        Map<String, Object> info = new HashMap<>();
        if (principal instanceof SysUserDetails sysUserDetails) {
            //把用户名设置到JWT中
            info.put(SecurityConst.KEY_USER_ID, sysUserDetails.getUserId());
            info.put(SecurityConst.KEY_DEPT_ID, sysUserDetails.getDeptId());
            // 认证身份标识(username:用户名;mobile:手机号;)
            if (StringUtils.hasLength(sysUserDetails.getAuthenticationIdentity())) {
                // 设置认证标识
                info.put(SecurityConst.KEY_AUTHENTICATION_IDENTITY, sysUserDetails.getAuthenticationIdentity());
            }
            // 刷新类型
            if (StringUtils.hasLength(sysUserDetails.getRefreshType())) {
                // 设置刷新类型
                info.put(SecurityConst.KEY_REFRESH_TYPE, sysUserDetails.getAuthenticationIdentity());
            }
        } else if (principal instanceof MemberUserDetails memberUserDetails) {
            info.put("memberId", memberUserDetails.getMemberId());
//            info.put("userName", memberUserDetails.getUsername());
            // 认证身份标识(mobile:手机号；openId:开放式认证系统唯一身份标识)
            if (StrUtil.isNotBlank(memberUserDetails.getAuthenticationIdentity())) {
                info.put(SecurityConst.KEY_AUTHENTICATION_IDENTITY, memberUserDetails.getAuthenticationIdentity());
            }
        }

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
